package lesson.ch5;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class IndexDBDao implements IIndexDao {
	private Connection conn;
	public Connection getConn() {
		return conn;
	}

	public void setConn(Connection conn) {
		this.conn = conn;
	}

	private DataSource ds;

	public DataSource getDs() {
		return ds;
	}

	public void setDs(DataSource ds) {
		this.ds = ds;
	}

	public Map<String, ArrayList<String>> load() {
		Statement stat = null;
		ResultSet rs = null;
		String file = null;
		String path = null;
		conn = ds.getConn();
		Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
		try {
			stat = conn.createStatement();
			rs = stat.executeQuery("select file_name,full_path from index_db");
			while (rs.next()) {
				file = rs.getString("file_name");
				path = rs.getString("full_path");
				if (map.containsKey(file))
					map.get(file).add(path);
				else {
					ArrayList<String> arr = new ArrayList<String>();
					arr.add(path);
					map.put(file, arr);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	public void unload(Map<String, ArrayList<String>> map) {
		Statement stat = null;
		String file = null;
		String path = null;
		String sql = null;
		conn = ds.getConn();
		try {
			conn.setAutoCommit(true);
			stat = conn.createStatement();
			stat.executeQuery("truncate table index_db");
			for (String key : map.keySet()) {
				for (String value : map.get(key)) {
					file = key;
					path = value;
					sql = "insert into index_db(file_name,full_path)values('" + file + "','" + path + "')";
					//System.out.println(sql);
					stat.executeUpdate(sql);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
		Connection conn = null;
		for (int i = 0; i <= 10; i++) {
			ArrayList<String> arr = new ArrayList<String>();
			arr.add("path" + i);
			map.put("file" + i, arr);
		}
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.21.215:1523/tas_taf", "nick", "nick");
		} catch (Exception e) {
			e.printStackTrace();
		}
		IndexDBDao db = new IndexDBDao();
		DataSource ds = new DataSource();
		ds.setUser("nick");
		ds.setUrl("jdbc:oracle:thin:@192.168.21.215:1523/tas_taf");
		ds.setPass("nick");	
		db.setDs(ds);
		db.unload(map);
		map = db.load();
		for (String key : map.keySet()) {
			for (String val : map.get(key)) {
				System.out.println(key + "-" + val);
			}
		}
	}

}
